package com.spring.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.boot.entity.ProvinceCity;
import com.spring.boot.mapper.CityMapper;
import com.spring.boot.service.CityService;
import com.spring.boot.utils.CityId;
import com.spring.boot.vo.CityVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, ProvinceCity> implements CityService {
    @Autowired
    private CityMapper cityMapper;
    @Override
    public CityVo getCityInfo(QueryWrapper<ProvinceCity> queryWrapper) {
        queryWrapper.orderByDesc("create_time").last("LIMIT 0,10");
        List<ProvinceCity> citys = cityMapper.selectList(queryWrapper);
        //根据citycode对查询结果进行降序排序。
        List<ProvinceCity> orderedCitys = citys.stream()
                .sorted((o1, o2) -> Integer.parseInt(o2.getCityCode()) - Integer.parseInt(o1.getCityCode())).collect(Collectors.toList());
        CityVo cityVo = new CityVo();
        ArrayList<String> cityList = new ArrayList<>();
        ArrayList<String> confirmedList = new ArrayList<>();
        ArrayList<String> confirmedRelativeList = new ArrayList<>();
        ArrayList<String> cruedList = new ArrayList<>();
        for (ProvinceCity city : orderedCitys) {
            cityList.add(city.getCity());
            confirmedList.add(city.getConfirmed());
            confirmedRelativeList.add(city.getConfirmedRelative());
            cruedList.add(city.getCrued());
        }
        cityVo.setCategory(cityList);
        cityVo.setLineData(confirmedList);
        cityVo.setBarData(confirmedRelativeList);
        cityVo.setRateData(cruedList);
        return cityVo;
    }

    @Override
    public Map getCitiesTrend() {
        HashMap<String, List<?>> map = new HashMap<>();
        List<String> dateList = new ArrayList<>();
        for (CityId cityId : CityId.values()) {
            QueryWrapper<ProvinceCity> cityQueryWrapper = new QueryWrapper<>();
            cityQueryWrapper.eq("city", cityId.getCityName()).orderByAsc("create_time");//根据城市名字查询
            List<ProvinceCity> cityList = cityMapper.selectList(cityQueryWrapper);
            List<Integer> confirmList = new ArrayList<>();
            for (ProvinceCity city : cityList) {
                confirmList.add(Integer.valueOf(city.getCurConfirm()));
                if (!dateList.contains(city.getCreateTime())) {
                    dateList.add(city.getCreateTime());
                }
            }
            map.put(cityId.getCityName(), confirmList);
        }
        map.put("date", dateList);
        return map;
    }
}
